package controllers

import (
	"encoding/json"
	"net/http"
	"strings"

	"gitee.com/go-micro-services/common"
	"gitee.com/go-micro-services/nacos-go-micro-gin/conf"
	"github.com/gin-gonic/gin"
	"github.com/nacos-group/nacos-sdk-go/v2/model"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
)

var statusOK = http.StatusOK
var statusBadRequest = http.StatusBadRequest

type ApiController struct{}

func (con ApiController) Index(c *gin.Context) {
	params := vo.GetAllServiceInfoParam{
		GroupName: conf.NacosGroupName,
		PageNo:    1,
		PageSize:  10,
	}
	list, err := common.NacosGetAllService(params)
	// 错误处理
	if err != nil {
		// 错误处理
		c.JSON(statusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}
	// 正常响应
	c.JSON(statusOK, list)
}

func (con ApiController) FindService(c *gin.Context) {
	params := vo.GetServiceParam{
		ServiceName: conf.NacosServiceName,
		GroupName:   conf.NacosGroupName,
	}
	list, err := common.NacosGetService(params)
	// 错误处理
	if err != nil {
		// 错误处理
		c.JSON(statusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}
	// 正常响应
	c.JSON(statusOK, list)
}

func (con ApiController) GetConfig(c *gin.Context) {
	content, err := common.NacosGetConfig(conf.NacosDataId, conf.NacosGroup)
	// 错误处理
	if err != nil {
		c.JSON(statusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}
	var contentJson map[string]interface{}
	// 解码JSON字符串到map
	err = json.Unmarshal([]byte(content), &contentJson)
	// 错误处理
	if err != nil {
		c.JSON(statusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}
	// 正常响应
	c.JSON(statusOK, contentJson)
}

func (con ApiController) SearchConfig(c *gin.Context) {
	// 构造搜索参数
	params := vo.SearchConfigParam{
		Search:   "blur",
		DataId:   conf.NacosDataId,
		Group:    conf.NacosGroup,
		PageNo:   1,
		PageSize: 10,
	}
	// 调用接口获得结果
	var currentPage *model.ConfigPage
	var err error
	if currentPage, err = common.NacosSearchConfig(params); err != nil {
		c.JSON(statusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}
	// 格式转化
	var jsonBytes []byte
	if jsonBytes, err = json.Marshal(currentPage); err != nil {
		c.JSON(statusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}
	// 处理特殊字符
	str := strings.ReplaceAll(string(jsonBytes), " ", "")
	str = strings.ReplaceAll(str, "\\n", "")
	str = strings.ReplaceAll(str, "\\", "")
	str = strings.ReplaceAll(str, `"{`, "{")
	str = strings.ReplaceAll(str, `}"`, "}")
	// 转换成 json
	var result map[string]interface{}
	if err = json.Unmarshal([]byte(str), &result); err != nil {
		c.JSON(statusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}
	c.JSON(statusOK, result)
}
